package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.dao.jdbc.TemperatureJdbc;
import com.wuseguang.springcloud.service.TemperatureService;
import com.wuseguang.springcloud.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 学生体温表 服务实现类
 * </p>
 *
 * @author
 * @since 2020-07-06
 */
@Service
public class TemperatureServiceImpl implements TemperatureService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TemperatureJdbc temperatureJdbc;

    @Override
    public Result findStudentTemperature(String schoolId, String time) {

        String sql = "select c.id,c.`name` from classes c " +
                "left join grade g on(c.grade_id=g.id) where c.school_id = ? AND c.graduation=0 and g.other=0 ORDER BY g.id";
        //查询学校班级
        List<Map<String, Object>> classList = temperatureJdbc.queryListMap(sql, schoolId);
        //循环班级
        for (Map<String, Object> map : classList) {

            sql = "select id,student_name, monitoring_time,ti_wen,state,head_portrait  from ( " +
                    " select s.id,s.student_name,DATE_FORMAT(t.monitoring_time,'%H:%i') monitoring_time,ti_wen,t.state,s.head_portrait,t.id tid from  student s  " +
                    " left join  temperature t on(s.id=t.student_id and to_days(t.monitoring_time) =" +
                    " to_days("+ (StringUtils.isEmpty(time) ? "now()" : "'" + time + "'") +"))  where s.class_id =? order by t.id desc " +
                    " ) as t group by t.id";

            List<Map<String, Object>> studentlist = temperatureJdbc.queryListMap(sql, map.get("id"));

            sql = "select  IFNULL(sum(if(t.id is null,1,0)),0) `not`,IFNULL(sum(if(t.state=1,1,0)),0) `abnormal`   from  student s left join   " +
                    "temperature t on(s.id=t.student_id and to_days(t.monitoring_time) = to_days(" + (StringUtils.isEmpty(time) ? "now()" : "'" + time + "'") + ")) " +
                    " where s.class_id = ? ";
            //未检测跟异常
            Map<String, Object> noMap = temperatureJdbc.queryMap(sql, map.get("id"));
            //未检测数据
            Integer not = Integer.valueOf(noMap.get("not").toString());
            map.put("studentlist", studentlist);
            map.put("not", not);
            //异常数据
            map.put("abnormal", Integer.valueOf(noMap.get("abnormal").toString()));
            map.put("total", studentlist.size());
        }

        return new Result(classList);
    }
}
